package com.foreknow.elm.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 处理字符编码
        //设置从服务器端向客户端返回的内容的类型   MIME类型: text/html
        response.setContentType("application/json;charset=UTF-8");
        //客户端向服务器端请求的编码格式（否则会产生乱码） 默认：IOS8859-1
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        //2. 获取到客户端发送的请求路径（URL的部分路径）
        String path = request.getServletPath(); //    /Controller类名/Controller方法名
        //3. 根据获取到的路径得到类名和方法名
        String className = path.substring(1,path.lastIndexOf("/"));
            String methodName = path.substring(path.lastIndexOf("/")+1);
            try {
                //4. 通过Class.forName()获取到Controller中类的信息
                Class clazz = Class.forName("com.foreknow.elm.controller." + className);
                //将获取到的类转换为对象(LoginController的对象)
                Object controller = clazz.newInstance();
                //5. 获取方法
                Method method = clazz.getMethod(methodName,new Class[]{HttpServletRequest.class});
            //6. 调用方法
            Object result = method.invoke(controller,new Object[]{request});
            //7. 将结果result以JSON的数据格式响应给客户端浏览器
            ObjectMapper objectMapper = new ObjectMapper();
            out.print(objectMapper.writeValueAsString(result));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
